//
//  ScanViewController.m
//  hellomui
//
//  Created by zhangtao on 15/11/12.
//  Copyright © 2015年 zt.td. All rights reserved.
//

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIWebViewDelegate>
@property(nonatomic,strong)UIWebView *web;

@property (weak, nonatomic) IBOutlet UIView *viewPreview;

@property (weak, nonatomic) IBOutlet UILabel *lblStatus;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
- (IBAction)startStopReading:(id)sender;


@property (strong, nonatomic) UIView *boxView;
@property (nonatomic) BOOL isReading;
@property (strong, nonatomic) CALayer *scanLayer;

-(BOOL)startReading;
-(void)stopReading;


@property (nonatomic, strong) AVCaptureSession *captureSession;

@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;

@end

@implementation ScanViewController
- (IBAction)back:(id)sender {
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"开始扫描");
    _captureSession = nil;
    _isReading = NO;
    
    if (!_isReading) {
        if ([self startReading]) {
            [_startBtn setTitle:@"Stop" forState:UIControlStateNormal];
            [_lblStatus setText:@"Scanning for QR Code"];
        }
    }
    else{
        [self stopReading];
        [_startBtn setTitle:@"Start!" forState:UIControlStateNormal];
    }
    
    _isReading = !_isReading;
    
}

- (BOOL)startReading {
    NSError *error;
    
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    
    _captureSession = [[AVCaptureSession alloc] init];
    
    [_captureSession addInput:input];
    
    [_captureSession addOutput:captureMetadataOutput];
    
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    
    captureMetadataOutput.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];//[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
    _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    
    [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    [_videoPreviewLayer setFrame:CGRectMake(-8, -5, MAIN_WIDTH + 8, MAIN_HEIGHT)];
    
    [_viewPreview.layer addSublayer:_videoPreviewLayer];
    
    captureMetadataOutput.rectOfInterest = CGRectMake(0.3f, 0.3f, 0.6f, 0.4f);
    
    _boxView = [[UIView alloc] initWithFrame:CGRectMake(MAIN_WIDTH * 0.2f, MAIN_HEIGHT * 0.3f, MAIN_WIDTH - MAIN_WIDTH * 0.4f, MAIN_HEIGHT - MAIN_HEIGHT * 0.7f)];
    _boxView.layer.borderColor = [UIColor greenColor].CGColor;
    _boxView.layer.borderWidth = 2.0f;
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(_boxView.frame)+10,  MAIN_WIDTH, 30)];//(MAIN_WIDTH *0.2f,CGRectGetMaxY(_boxView.frame)+10,  MAIN_WIDTH - MAIN_WIDTH * 0.4f, 30)];
    [label setTextAlignment:NSTextAlignmentCenter];
 
    label.text = @"请将二维码放入框内，即可自动扫描";
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:14];
    label.numberOfLines = 0;

    [_viewPreview addSubview:label];
    
    [_viewPreview addSubview:_boxView];
    
    //.扫描线
    _scanLayer = [[CALayer alloc] init];
    _scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
    _scanLayer.backgroundColor = [UIColor greenColor].CGColor;
    
    [_boxView.layer addSublayer:_scanLayer];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.05f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    
    [timer fire];
    
    [_captureSession startRunning];
    
    
    return YES;
}

- (IBAction)startStopReading:(id)sender {
   
}

-(void)stopReading{
    [_captureSession stopRunning];
    _captureSession = nil;
    [_scanLayer removeFromSuperlayer];
    [_videoPreviewLayer removeFromSuperlayer];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        NSLog(@"值%@",metadataObj.stringValue);
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            [_lblStatus performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
            
            [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
            _isReading = NO;
            NSLog(@"%@~~~%@",_lblStatus.text,metadataObj);
            NSString *url = [NSString stringWithFormat:@"%@",_lblStatus.text];
            [self websss:url];
        }
    }
}
-(void)websss:(NSString *)str{
    
   
    dispatch_async(dispatch_get_main_queue(), ^{
        self.loveStu.webUrl = str;
        self.loveStu.isScan = YES;
        [self dismissViewControllerAnimated:YES completion:nil];
//        _web = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, MAIN_WIDTH, MAIN_HEIGHT)];
//        [_web loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
//        _web.delegate = self;
//        [_viewPreview addSubview:_web];
    });
//
//   

}

- (void)moveScanLayer:(NSTimer *)timer
{
    CGRect frame = _scanLayer.frame;
    if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
        frame.origin.y = 0;
//        _scanLayer.frame = frame;
        _scanLayer.frame = CGRectMake(0, -40, _boxView.bounds.size.width, 1);

    }else{
        
        frame.origin.y += 5;
        
        [UIView animateWithDuration:0.1 animations:^{
            _scanLayer.frame = frame;
        }];
    }
}

- (BOOL)shouldAutorotate
{
    return NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
